import traceback
import json
import json
import requests
from flask import Flask, request, jsonify
import configparser
from redis.exceptions import RedisError
from public import *
from tools import *
mlog = MyLogger("web")
app = Flask(__name__)

@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({'status': 'ok', 'service': 'task_api'})


def keyword_search(message):
    access_key = "NjNhMmE5MmM4MTQ2MmUxYjY4Njc2YWUwLDExNTAsMTcxNTM5NTI3Nzk5MQ=="
    url = "https://ai-api.betteryeah.com/v1/public_api/rest_api/181a984dd558449b90fcbb39f4247155/execute_flow"
    data = {
        "inputs":{
        "message":message,
        }
    }
    headers = {
        "Content-Type":"application/json",
        "Access-Key":access_key,
        "Workspace-Id":"63a2a92c81462e1b68676ae0"
    }
    res = requests.post(url,data=json.dumps(data),headers=headers)
    data = json.loads(res.text)
    if data.get("code") == 200:
        status = 200
        msg = data.get("message")
        data = data["data"]["run_result"]
    else:
        status = 400
        msg = data["message"]
        data = None
    return status,msg,data

@app.route('/task', methods=['POST'])
def submit_task():
    mlog.info(f"flask-web-api:获取到请求:[{request.data}]")
    data = request.get_json()
    mlog.info(f"flask-web-api:获取到任务:[{data}]")
    # 参数校验
    if not data:
        mlog.info(f"flask-web-api:data参数异常")
        return jsonify({
            'code': 400,
            'message': '数据异常,检查不到data参数'
        }), 400
    # 参数校验
    try:
        request_id = data["request_id"]
        check_type = data["check_type"]
            # 10关键词搜索
            # 20产品方案检测
            # 30系统架构方案检测
            # 31系统详细设计方案检测
        keyword = data["keyword"] if check_type == 10 else None
        dingding_doc_link = data["dingding_doc_link"] if check_type >= 20 else None
        callback_url = data["callback_url"] if check_type >= 20 else None
        level = data["level"] if check_type >= 20 else None
        if check_type >= 20 and level.upper() not in ("A","B","C","D"):
            raise Exception("level不在ABCD中")
    except Exception as e:
        mlog.info(f"flask-web-api:data参数异常[{str(e)}]")
        return jsonify({
            'code': 400,
            'message': f'参数异常:[{str(e)}]'
        }), 400
    
    # 任务处理
    if check_type == 10:
        try:
            status,msg,res_data = keyword_search(keyword)
        except Exception as e:
            msg = f"[AI调用异常][{traceback.format_exc()}]"
            mlog.error("")
            status = 500
            res_data = None
        return jsonify({
            'code': status,
            'message': res_data or msg,
            'request_id': data['request_id']
        }) , 200
    else:
        try:
            # Redis连接和任务推送
            redis_client.safe_rpush(REDIS_TASK_LIST_KEY, json.dumps(data))
            mlog.info(f"flask-web-api:任务已添加到redis:[{data}]")
            return jsonify({
                'code': 200,
                'message': 'Task accepted',
                'request_id': data['request_id']
            })
        except RedisError as e:
            mlog.info(f"flask-web-api:程序异常:[{e}]")
            return jsonify({
                'code': 503,
                'request_id': data['request_id'],
                'message': f'Redis service unavailable: {str(e)}'
            }), 503
        except Exception as e:
            mlog.info(f"flask-web-api:程序异常:[{e}]")
            return jsonify({
                'code': 500,
                'request_id': data['request_id'],
                'message': f'任务录入异常: {str(e)}'
            }), 500

if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port=50012,
        debug=mconfig.get('flask', 'debug')
    )